<template>
	<view class="container">
		<!-- #ifndef MP-WEIXIN -->
		<!-- 顶部导航栏 -->
		<navBar :isIndex="true" title="MojitoBlog"></navBar>
		<!-- #endif -->
		<!-- #ifdef MP-WEIXIN -->
		<midell-box :current-page="0"></midell-box>
		<!-- #endif -->

		<!-- 搜索栏 -->
		<u-search
			:showAction="false"
			placeholder="找不到就搜呗"
			height="4.5vh"
			v-model="keyword"
			@search="to_search"
		></u-search>

		<!-- tab 栏 -->
		<u-tabs
			:list="classifyList"
			keyName="classifyName"
			:current="current"
			@click="getTabbarIndex"
			lineColor="#7fa7d7"
			lineWidth="24"
		></u-tabs>

		<!-- 轮播图区域 -->
		<swiper class="swiper" :current="current" @change="getSwiperIndex" :style="{ height: height + 50 + 'px' }">
			<swiper-item v-for="(item, index) in classifyList" :key="item.id" class="swiper-item">
				<!-- 瀑布流组件 -->
				<u-waterfall :value="renderList[index]" ref="waterfall" class="waterfall">
					<template v-slot:left="{ leftList }">
						<view @click="toShowDetail(item)" class="water_item" v-for="(item, idx) in leftList" :key="idx">
							<view class="imgBox">
								<image @load="imgLoaded" :src="item.Blog.cover" mode="widthFix"></image>
							</view>
							<view class="title">{{ item.Blog.title }}</view>
							<view class="publisher">
								<u-row customStyle="margin-bottom: 10px">
									<u-col span="2">
										<view class="demo-layout bg-purple left">
											<u--image
												:src="item.Blog.userAvatar || '../../static/logo.png'"
												shape="circle"
												width="5vw"
												height="5vw"
											></u--image>
										</view>
									</u-col>
									<u-col span="5">
										<view class="demo-layout bg-purple-light">{{ item.Blog.userName }}</view>
									</u-col>
									<u-col span="5">
										<view class="demo-layout bg-purple-dark right">
											浏览{{ item.Blog.read_count }}次
										</view>
									</u-col>
								</u-row>
							</view>
						</view>
					</template>
					<template v-slot:right="{ rightList }">
						<view
							@click="toShowDetail(item)"
							class="water_item"
							v-for="(item, idx) in rightList"
							:key="idx"
						>
							<view class="imgBox">
								<image @load="imgLoaded" :src="item.Blog.cover" mode="widthFix"></image>
							</view>
							<view class="title">{{ item.Blog.title }}</view>
							<view class="publisher">
								<u-row customStyle="margin-bottom: 10px">
									<u-col span="2">
										<view class="demo-layout bg-purple left">
											<u--image
												:src="item.Blog.userAvatar || '../../static/logo.png'"
												shape="circle"
												width="5vw"
												height="5vw"
											></u--image>
										</view>
									</u-col>
									<u-col span="5">
										<view class="demo-layout bg-purple-light">{{ item.Blog.userName }}</view>
									</u-col>
									<u-col span="5">
										<view class="demo-layout bg-purple-dark right">
											浏览{{ item.Blog.read_count }}次
										</view>
									</u-col>
								</u-row>
							</view>
						</view>
					</template>
				</u-waterfall>

				<!-- 页面切换的加载页 -->
				<u-loading-page :loading="isShiftLoading"></u-loading-page>
				<!-- 底部loading -->
				<u-loadmore
					v-if="renderList[index] && renderList[index].length"
					height="40px"
					marginTop="0"
					marginBottom="0"
					:status="status"
				/>
				<!-- v-show 是为了 加载页 和 空 不同时出现 -->
				<u-empty v-else v-show="!isShiftLoading" mode="list" text="暂无数据"></u-empty>
			</swiper-item>
		</swiper>

		<!-- 占位盒子 -->
		<view class="footer"></view>
	</view>
</template>

<script>
import { getClassify, getBlogsByClassifyId } from '@/config/api.js';
export default {
	data() {
		return {
			keyword: '',
			current: 0,
			// 分类信息
			classifyList: [],
			// 渲染结构的列表
			renderList: [],
			// 轮播图高度
			height: 0,
			// 底部上拉加载的状态值
			status: 'loadmore',
			// 初始展示多少条数据
			limit: 10,
			// 各个分类的博客总数
			count: [],
			// 是否正在加载
			isLoading: false,
			// 是否计算轮播图高度
			isCal: false,
			// 是否处于切换加载状态
			isShiftLoading: false
		};
	},
	// 页面加载的生命周期
	onLoad() {
		// 页面加载时获取分类信息
		this.getClassifyInfo();
	},
	// 解决切换页面导致首页报错的问题
	onShow() {
		this.isCal = false;
	},
	onHide() {
		this.isCal = true;
	},
	// 滚动到底部的生命周期
	onReachBottom() {
		// 重新计算轮播图高度
		this.imgLoaded();
		// 正在加载，返回
		if (this.isLoading) return;
		// 若没有数据，不执行loading，直接return
		if (this.limit >= this.count[this.current]) {
			this.status = 'nomore';
			return;
		} else {
			this.status = 'loadmore';
		}
		this.isLoading = true;
		// 若还有数据
		this.status = 'loading';
		setTimeout(async () => {
			this.limit += 10;
			await this.getBlogsByClassifyId(this.classifyList[this.current].id, this.limit);
			this.isLoading = false;
			// if (this.limit >= this.count[this.current]) {
			// 	this.status = 'nomore';
			// } else {
			// 	this.status = 'loadmore';
			// }
		}, 300);
	},
	methods: {
		// 搜索
		to_search() {
			uni.navigateTo({
				url: `/subpages/search/search?keyword=${this.keyword}`
			});
			this.keyword = '';
		},
		// 点击 tab 栏，获取索引
		getTabbarIndex(e) {
			this.current = e.index;
		},
		// 轮播图的索引（切换轮播图）
		async getSwiperIndex(e) {
			this.current = e.detail.current;
			// 切换轮播图后重置 请求数据
			this.limit = 10;
			// 重新获取轮播图高度
			this.imgLoaded();
			// 如果已有数据，不必重复请求
			if (this.renderList[this.current]) return;
			// 开启切换loading
			this.isShiftLoading = true;
			// #ifndef MP-WEIXIN
			// 根据分类id获取博客
			await this.getBlogsByClassifyId(this.classifyList[this.current].id, this.limit);
			// 根据数据的数量动态改变底部的提示文本
			if (this.renderList[this.current].length < 10) {
				this.status = 'nomore';
			} else {
				this.status = 'loadmore';
			}
			// 关闭切换loading
			this.isShiftLoading = false;
			// #endif
			// #ifdef MP-WEIXIN
			uni.request({
				url: 'https://eggblog.bluej.cn/api/blog/searchByClassifyId',
				data: {
					id: this.classifyList[this.current].id,
					offset: 1,
					limit: this.limit || 10,
					projectId: 155
				},
				success: res => {
					this.count[this.current] = res.data.data.count;
					this.$set(this.renderList, this.current, res.data.data.rows);
					// 根据数据的数量动态改变底部的提示文本
					if (this.renderList[this.current].length < 10) {
						this.status = 'nomore';
					} else {
						this.status = 'loadmore';
					}
					// 关闭切换loading
					this.isShiftLoading = false;
				}
			});
			// #endif
		},
		// 获取分类信息，同时初始化数据
		async getClassifyInfo() {
			// 开启切换loading
			this.isShiftLoading = true;
			// #ifndef MP-WEIXIN
			const res = await getClassify();
			this.classifyList = res.rows;
			// 把分类信息保存到 vuex
			this.$store.commit('setClassifyList', this.classifyList);
			// 页面加载默认显示第一页
			this.getBlogsByClassifyId(this.classifyList[0].id, this.limit);
			// 展示半秒的loading效果
			setTimeout(() => {
				this.isShiftLoading = false;
			}, 500);
			// #endif
			// #ifdef MP-WEIXIN
			uni.request({
				url: 'https://eggblog.bluej.cn/api/classify/get',
				data: {
					projectId: 155
				},
				success: res => {
					this.classifyList = res.data.data.rows;
					// 把分类信息保存到 vuex
					this.$store.commit('setClassifyList', this.classifyList);
					// 页面加载默认显示第一页
					this.getBlogsByClassifyId(this.classifyList[0].id, this.limit);
					// 展示半秒的loading效果
					setTimeout(() => {
						this.isShiftLoading = false;
					}, 500);
				}
			});
			// #endif
		},
		// 根据分类id获取博客
		async getBlogsByClassifyId(id, limit) {
			// #ifndef MP-WEIXIN
			const res = await getBlogsByClassifyId(id, limit);
			this.count[this.current] = res.count;
			// vue2 对于后添加的数据，默认不做响应式，故需要调用api实现响应式
			this.$set(this.renderList, this.current, res.rows);
			// 一上来加载数据，先判断是否还有数据可以加载
			if (this.limit >= this.count[this.current]) {
				this.status = 'nomore';
			}
			// #endif
			// #ifdef MP-WEIXIN
			uni.request({
				url: 'https://eggblog.bluej.cn/api/blog/searchByClassifyId',
				data: {
					id: id,
					offset: 1,
					limit: limit || 10,
					projectId: 155
				},
				success: res => {
					this.count[this.current] = res.data.data.count;
					this.$set(this.renderList, this.current, res.data.data.rows);
					if (this.limit >= this.count[this.current]) {
						this.status = 'nomore';
					}
				}
			});
			// #endif
		},
		// 图片加载时 获取瀑布流组件的高度
		imgLoaded() {
			// 切换页面后不进行计算
			if (this.isCal) return;
			// 获取瀑布流的节点信息
			uni.createSelectorQuery()
				.selectAll('.waterfall')
				.boundingClientRect(res => {
					// 当前瀑布流组件高度
					this.height = +res[this.current].height;
				})
				.exec();
		},
		// 下拉刷新
		async onPullDownRefresh() {
			// 重置数据
			this.limit = 10;
			this.current = 0;
			this.renderList = [];
			this.status = 'loadmore';
			// 置空 瀑布流组件内部的数据
			this.$refs.waterfall.forEach(vc => vc.clear());
			// 重新发送请求
			await this.getClassifyInfo();
			setTimeout(() => {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		// 跳转内容详情页,携带博客id
		toShowDetail(item) {
			uni.navigateTo({
				url: `/subpages/detail/detail?blogid=${item.blogId}`
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.container {
	height: 100vh;
	::v-deep .u-search {
		margin: 0.6vh 1vw 0 !important;
	}
	.swiper {
		position: relative;
		box-sizing: border-box;
		width: 100%;
		min-height: 80vh;
		padding: 6px;
		.water_item {
			box-sizing: border-box;
			overflow: hidden;
			box-shadow: rgba(100, 100, 111, 0.2) 0px 7px 29px 0px;
			margin: 0 auto 3vw;
			border-radius: 3vw;
			padding: 1.8vw 1.8vw 0;
			width: 94%;
			.imgBox {
				overflow: hidden;
				image {
					width: 100%;
					border-radius: 1.8vw;
				}
			}
			.publisher {
				.left {
					margin-left: 2vw;
					width: 5vw;
					height: 5vw;
				}
				.right {
					font-size: 14px;
					color: #666;
					text-align: center;
				}
				.bg-purple-light {
					width: 18vw;
					overflow: hidden;
					white-space: nowrap;
					text-overflow: ellipsis;
				}
			}
			.title {
				width: 42vw;
				margin: 1vw auto 1.5vw;
			}
		}
	}
	.footer {
		width: 100%;
		/* #ifndef MP-WEIXIN */
		height: 50px;
		/* #endif */
		/* #ifdef MP-WEIXIN */
		height: 70px;
		/* #endif */
	}
	::v-deep .u-empty {
		margin-top: 3vh !important;
	}
	.u-loading-page {
		z-index: 999;
	}
}
</style>
